package com.netty.quartz.controller;

import com.netty.common.constant.Constants;
import com.netty.common.entity.result.Result;
import com.netty.common.enums.ExceptionEnum;
import com.netty.quartz.entity.SysJob;
import com.netty.quartz.service.ISysJobService;
import com.netty.quartz.util.CronUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author LiuXiaoYu
 * @date 2021/10/15- 22:15
 */
@RestController
@RequestMapping("/sys/job")
public class SysJobController {

    @Autowired
    private ISysJobService sysJobService;

    @PostMapping("/addJob")
    public Result<?> addJob(@RequestBody @Validated SysJob sysJob){
        //校验Cron表达式是否正确
        if (!CronUtils.isValid(sysJob.getCronExpression())){
            return Result.error(ExceptionEnum.ERROR,"新增任务'" + sysJob.getJobName() + "'失败，Cron表达式不正确");
        }
        //校验反射调用的方法名是否正确
        if (StringUtils.containsIgnoreCase(sysJob.getInvokeTarget(), Constants.LOOKUP_RMI)){
            return Result.error(ExceptionEnum.ERROR,  "新增任务'" + sysJob.getJobName() + "'失败，目标字符串不允许'rmi://'调用");
        }
        int row = sysJobService.addJob(sysJob);
        if (row>0){
            return Result.success("新增任务成功");
        }
        return Result.error("新增任务失败");
    }
}
